import { Dropdown, message } from "antd";
import { UserStatus,UserInfoDlg } from "../index";
import { createUserDropdownStyles, defaultTheme } from "../../static/styles/dropDown";
import { memo, useRef, useState } from "react";
import {InfoCircleFilled,MessageFilled,UserAddOutlined} from '@ant-design/icons';
import { useAppDispatch, useAppSelector } from "../../utils/storeHook/storeHook";
import http from "../../utils/http";
import api from "../../api";
import kbAvatar from '../../static/imgs/kbAvatar.png'
import { setPrivateChat } from "../../store/modules/authStore";
import { useNavigate } from "react-router-dom";
import { setServerId } from "../../store/modules/channelStore";

type UserActionItem = {
    key: string;
    label: string;
    icon?: React.ReactNode;
    type?: string;
    disabled?: boolean;
    onClick?: () => void;
};

interface ServerUsers {
    avatar_url: string,
    username: string,
    user_id:string,
    server_id:string,
    role:string,
    joined_at:string,
    guest_id:string,
    membership_id:string,
    can_leave:boolean,
    status:string,
    dropDownVis:boolean,
    isFriend:boolean,
}

const User = memo(({userItem,onClick}:{userItem:ServerUsers,onClick?:Function})=>{
    const styles = createUserDropdownStyles(defaultTheme)
    const dispatch = useAppDispatch()
    const navigate = useNavigate()

    const curUserId = useAppSelector(state=>state.auth.user_id)
    const [messageApi, contextHolder] = message.useMessage();

    const [hoveredKey, setHoveredKey] = useState<string | null>(null);
    const [userDtlDlgVis,setUserDtlDlgVis] = useState(false)
    const [dtlDlgUserId,setDtlDlgUserId] = useState('')
    const [dropDownVis,setDropDownVis] = useState(false)
    const dropDownRef = useRef<HTMLDivElement>(null)
    
    function handleOnClick(){
        onClick && onClick(userItem.user_id)
        if(userItem.guest_id || userItem.user_id == curUserId) return
        setDropDownVis(!dropDownVis)
        setTimeout(()=>{
            dropDownRef.current?.focus()
        },1)
        
    }

    // 用户操作菜单配置
    const userActions: UserActionItem[] = [
        {
            key: 'message',
            label: '发送私信',
            icon: <MessageFilled />,
            disabled: !userItem.isFriend, // 如果不是好友则禁用
            onClick: () => handlePrivateMessage(),
        },
        {
            key: 'add-friend',
            label: '添加好友',
            icon: <UserAddOutlined />,
            disabled: userItem.isFriend, // 如果已是好友则禁用
            onClick: () => handleAddFriend(),
        },
        {
            key: 'profile',
            label: '查看资料',
            icon: <InfoCircleFilled />,
            onClick: () => viewUserProfile()
        },
        // { key: 'divider-1', label: '', type: 'divider' },
        // {
        //   key: 'block',
        //   label: '屏蔽用户',
        //   type: 'danger',
        //   onClick: () => blockUser()
        // }
    ];

    const handlePrivateMessage = () => {
        console.log('发起私信:', userItem.user_id);
        // 实际业务中跳转到私信界面或打开私信弹窗
        setDropDownVis(false)
        dispatch(setPrivateChat(userItem.user_id))
        dispatch(setServerId('private'))
        navigate('/private')
    };

    const handleAddFriend = () => {
        // 发送好友请求API调用
        http.post(api.friend.addFriend,{friend_id:userItem.user_id}).then(()=>{
            messageApi.success('已发送好友申请')
        }).catch(err=>{
            messageApi.error(err.message)
        })
        setDropDownVis(false)
    };

    const viewUserProfile = () => {
        setUserDtlDlgVis(true)
        setDtlDlgUserId(userItem.user_id)
        setDropDownVis(false)
        
        // 打开用户资料弹窗
    };

    // const blockUser = () => {
    //     console.log('屏蔽用户:', userItem.user_id);
    //     // 调用屏蔽API
    // };

    // 菜单项样式处理
    const getActionStyle = (item: UserActionItem): React.CSSProperties => {
        const baseStyle = styles.listItem

        if (hoveredKey === item.key && !item.disabled) {
            return {
                ...baseStyle,
                backgroundColor: item.type === 'danger' ? 'rgba(237, 66, 69, 0.1)' : '#3a3c42'
            };
        }

        return baseStyle;
    };
    return (
        <>
            {contextHolder}
            <Dropdown
                trigger={['click']}
                placement="bottomRight"
                open={dropDownVis}
                popupRender={()=>
                    <div 
                        style={styles.list} 
                        ref={dropDownRef} 
                        tabIndex={0} 
                        onBlur={()=>setDropDownVis(false)}>
                        {userActions.map(item => (
                            item.key.includes('divider') ? 
                            (
                                <div 
                                    key={item.key} 
                                    style={{
                                    height: '1px',
                                    backgroundColor: '#40444b',
                                    margin: '4px 0'
                                }} />
                            ) : 
                            (
                                !item.disabled&&<div
                                    key={item.key}
                                    style={getActionStyle(item)}
                                    onClick={() => !item.disabled && item.onClick?.()}
                                    onMouseEnter={() => !item.disabled && setHoveredKey(item.key)}
                                    onMouseLeave={() => setHoveredKey(null)}
                                >
                                    {item.icon && <span style={{ fontSize: '16px' }}>{item.icon}</span>}
                                    {item.label}
                                </div>
                            )
                        ))}
                    </div>
                }
            >
                <div className='channel_user_item' onClick={()=>handleOnClick()}>
                    <div className='channel_user_item_avatar'>
                        <img loading='lazy' src={userItem.avatar_url || kbAvatar} alt="" />
                        <UserStatus userStatus={userItem.status} size={12}></UserStatus>
                    </div>
                    <div className='channel_user_item_name'>{userItem.username}</div>
                </div>
            </Dropdown>
            <UserInfoDlg user_id={dtlDlgUserId} visible={userDtlDlgVis} onClose={() => setUserDtlDlgVis(false)} />
        </>
    )
})

export default User